package com.dy.lock.screen.component.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import com.dy.lock.screen.component.LockScreenComponent;
import com.dy.lock.screen.constants.TransmissionCode;
import com.dy.lock.screen.exception.ServerDisponseException;
import com.dy.lock.screen.pojo.LockScreenInfo;
import com.dy.lock.screen.scoket.Head;
import com.dy.lock.screen.service.LockScreenService;
import com.dy.lock.screen.utils.CommonUtil;
import com.dy.lock.screen.vo.LockScreenVo;
import com.google.gson.Gson;

@Component("lockScreenComponent")
public class LockScreenComponentImpl implements LockScreenComponent {

	private static final Logger log = Logger
			.getLogger(LockScreenComponentImpl.class);

	private Gson gson;

	@Resource(name = "lockScreenService")
	private LockScreenService lockScreenService;

	public LockScreenComponentImpl() {
		gson = CommonUtil.gson();
	}

	@Override
	public List<LockScreenVo> getDyPicture(String body, Head head) {
		LockScreenVo vo = gson.fromJson(body, LockScreenVo.class);
		if (vo != null) {
			Integer currentPage = vo.getPageIndex(), pageSize = vo
					.getPageCount();
			Integer pageStart = 1;
			Integer pageEnd = 10;
			if (currentPage != null && pageSize != null) {
				pageStart = (currentPage - 1) * pageSize + 1;
				pageEnd = currentPage * pageSize;
			}

			List<LockScreenVo> voList = new ArrayList<LockScreenVo>();
			List<LockScreenInfo> queryList = this.lockScreenService.query(vo
					.getType(), pageStart, pageEnd, head);
			for (LockScreenInfo lockScreenInfo : queryList) {
				LockScreenVo lockScreenVo = new LockScreenVo();
				BeanUtils.copyProperties(lockScreenInfo, lockScreenVo);
				if (StringUtils.isNotBlank(lockScreenInfo.getPicPath())) {
					lockScreenVo.setPicPath(CommonUtil.getUrlPrefix()
							+ lockScreenInfo.getPicPath());
				}
				voList.add(lockScreenVo);
			}

			if (voList.size() > 0) {
				return voList;
			} else {
				throw new ServerDisponseException(
						TransmissionCode.NO_MORE_PICTURE.getCode(),
						TransmissionCode.NO_MORE_PICTURE.getMessage());
			}
		} else {
			log.info("requestId:" + head.getRequestId() + ",获取图库时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

}
